// pages/supplier/list/list.js
const supplierApi = require('../../../api/supplier')

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		loading: false,
		list: [],
		current: 1,
		size: 10,
		total: 0,
		keyword: ''
	},

	onLoad() {
		this.fetchList(true)
	},

	async fetchList(reset = false) {
		if (this.data.loading) return
		this.setData({ loading: true })
		try {
			const params = {
				current: reset ? 1 : this.data.current,
				size: this.data.size,
				keyword: this.data.keyword
			}
			const page = await supplierApi.getSuppliers(params)
			this.setData({
				list: page.records || [],
				total: page.total || 0,
				current: page.current || params.current
			})
		} catch (e) {
			wx.showToast({ title: '加载失败', icon: 'none' })
		} finally {
			this.setData({ loading: false })
			wx.stopPullDownRefresh()
		}
	},

	onPullDownRefresh() {
		this.fetchList(true)
	},

	onReachBottom() {
		if (this.data.list.length < this.data.total) {
			this.setData({ current: this.data.current + 1 })
			this.fetchList()
		}
	},

	toCreate() {
		wx.navigateTo({ url: '/pages/supplier/form/form' })
	},

	toEdit(e) {
		const { id } = e.currentTarget.dataset
		wx.navigateTo({ url: `/pages/supplier/form/form?id=${id}` })
	}
})